﻿#include "lister.h"
#include "ui_lister.h"

Lister::Lister(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Lister)
{
    ui->setupUi(this);

    model=new QStringListModel(this);
    ui->listView->setModel(model);
}

Lister::~Lister()
{
    delete ui;
}

void Lister::on_btn_pick_clicked()
{
    QString fileName=QFileDialog::getOpenFileName(this,QStringLiteral("选择文本文件"),
                                                  QString(),"Text (*.txt)");
    QFile file(fileName);
    if(file.open(QFile::ReadOnly | QFile::Text))
    {
        QTextStream stream(&file);
        ui->content->setPlainText(stream.readAll());
    }
}

void Lister::on_btn_process_clicked()
{
    QString content=ui->content->toPlainText();
    if(content.isEmpty())
        return;

    if(!lines.isEmpty())
        lines.clear();

    QTextStream stream(&content,QIODevice::ReadOnly);
    QString line;
    int count=0;
    while (stream.readLineInto(&line)) {
        count++;
        if(line.isEmpty())
            continue;

        if(!lines.contains(line))
            lines.append(line);
    }
    if(lines.isEmpty())
        return;

    model->setStringList(lines);
    QString summary=QStringLiteral("【总行数】") + QString::number(count)
            + "\t\t"
            + QStringLiteral("【有效行数】") + QString::number(lines.size());
    ui->status->setText(summary);
}

void Lister::on_btn_clean_clicked()
{
    ui->content->clear();
    model->setStringList(QStringList());
    ui->status->clear();
}

void Lister::on_btn_export_clicked()
{
    if(lines.isEmpty())
        return;

    QString fileName=Location::desktop + QString("/")
            + QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss") + ".txt";
    QFile file(fileName);
    if(file.open(QFile::WriteOnly | QFile::Text))
    {
        QTextStream stream(&file);
        foreach (QString line, lines) {
            stream << line << "\n";
        }
        stream.flush();
        file.close();
        QMessageBox::information(this,QStringLiteral("操作已完成"),
                                 QStringLiteral("文件已保存到 ") + fileName);
    }
}
